package com.hjlsoft.aftp.ins.handler;

import java.io.IOException;
import java.util.Map;

import com.hjlsoft.aftp.config.AftpConfig;
import com.hjlsoft.aftp.network.Request;
import com.hjlsoft.aftp.network.Response;
import com.hjlsoft.aftp.token.Token;
import com.hjlsoft.aftp.token.TokenManager;

public class CreateTokenInsHandle extends BaseInsHandle {

	private TokenManager tokenManger;

	@Override
	public void onInit(AftpConfig config, Map<String, Object> services) {
		tokenManger = (TokenManager)services.get("tokenManager");
	}

	public void execute(Request request, Response response) throws IOException {
		if (!assertLogin(request, response)) {
			return;
		}
		
		Token token = createToken(getLoginUsername(request));
		tokenManger.save(token, aftpService.getConfig().getTokenExpire());
		
		response.writeSuccessDataEnd(token.getId());
	}
	
	private Token createToken(String username) {
		String tokenId = tokenManger.makeTokenId();
		Token token = new Token();
		token.setCreateTime(System.currentTimeMillis());
		token.setId(tokenId);
		token.setUsername(username);
		return token;
	}

	public String getIns() {
		return "create_token";
	}

}
